package com.spark.gaea.config.service.easyzk;

import com.google.common.base.Preconditions;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Administrator
 */
public final class ConfigNodeEventListener implements CuratorListener {
	private static final Logger LOG = LoggerFactory.getLogger(ConfigNodeEventListener.class);
	private final ConfigNode configNode;

	public ConfigNodeEventListener(final ConfigNode configNode) {
		this.configNode = (ConfigNode) Preconditions.checkNotNull((Object) configNode);
	}

	@Override
	public void eventReceived(final CuratorFramework client, final CuratorEvent event) throws Exception {
		if (ConfigNodeEventListener.LOG.isDebugEnabled()) {
			ConfigNodeEventListener.LOG.debug(event.toString());
		}
		final WatchedEvent watchedEvent = event.getWatchedEvent();
		if (watchedEvent != null) {
			if (ConfigNodeEventListener.LOG.isDebugEnabled()) {
				ConfigNodeEventListener.LOG.debug(watchedEvent.toString());
			}
			if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
				boolean someChange = false;
				switch (watchedEvent.getType()) {
					case NodeChildrenChanged: {
						this.configNode.loadNode();
						someChange = true;
						break;
					}
					case NodeDataChanged: {
						this.configNode.loadKey(watchedEvent.getPath());
						someChange = true;
						break;
					}
				}
				if (someChange && this.configNode.getConfigLocalCache() != null) {
					this.configNode.getConfigLocalCache().saveLocalCache(this.configNode, this.configNode.getNode());
				}
			}
		}
	}
}
